<?php

namespace app\api\controller;

use app\common\server\Upload as uploadss;
use \think\facade\Db;
use OSS\Core\OssException;
use OSS\OssClient;
require_once '../extend/oss/autoload.php';

class Upload extends Base
{
    public function picture()
    {
        #获取表单上传文件
        $files = request()->file('file', '');
        if (empty($files)) {
            return $this->renderError("请上传图片");
        }
        $ext = ['jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG', 'gif', 'apk', 'mp3'];
        $type = substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], '.') + 1);
        if (!in_array($type, $ext)) {
            return $this->renderError("文件格式错误");
        }
        if ($_FILES['file']['size'] > 20971520) {
            return $this->renderError("上传文件不能超过20M");
        }
        #判断是否上传过
        $hash = $files->hash('sha1');
        $info = Db::name('picture')->where('token', $hash)->find();
        if ($info) {
            $data['path'] = imageUrl($info['imgurl']);
            $data['imgurl'] = $info['imgurl'];
            return $this->renderSuccess('上传成功', $data);
        } else {
            $object_file = 'storage/topic';
            // $accessKeyId = 'LTAI5tMLfretRWVDAdfXUGap';
            // $accessKeySecret = 'jXrHqyRO08sok3cAMhj5173knuw8YS';
            // $endpoint = 'http://oss-cn-beijing.aliyuncs.com';
            // $bucket = 'jidimowan';
            
            $accessKeyId = 'LTAI5tRJHd6Uj8J2eWDssf11';
            $accessKeySecret = 'zrfh3ZrmSAvf0ZJAiSUKoMU5LhEQfX';
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            $endpoint = 'http://oss-cn-beijing.aliyuncs.com';
            // 设置存储空间名称。
            $bucket = 'ouhechaowan';
            // 设置文件名称。
            $object = $object_file . '/' . date('Ymd') . '/' . sha1(date('YmdHis', time()) . uniqid()) . '.' . $type;
            // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
            $filePath = $_FILES['file']['tmp_name'];
            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $ossClient->uploadFile($bucket, $object, $filePath);
            } catch (OssException $e) {
                return $this->renderError("上传失败");
            }
            #新增数据
            $object = '/'.$object;
            $save_data['token'] = $hash;
            $save_data['imgurl'] = $object;
            $save_data['addtime'] = time();
            $save_data['status'] = 1;
            $res = Db::name('picture')->insertGetId($save_data);
            if ($res) {
                $data['path'] = imageUrl($object);
                $data['imgurl'] = $object;
                return $this->renderSuccess('上传成功', $data);
            } else {
                return $this->renderError('上传失败');
            }
        }
    }

    /**
     * 上传图片
     */
    public function picture_old()
    {
        // 获取表单上传文件
        $files = request()->file();
        if (empty($files['file'])) {
            return $this->renderError("请上传图片");
        }
        try {
            $ext = ['jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG'];
            $type = substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], '.') + 1);
            if (!in_array($type, $ext)) {
                return $this->renderError("文件格式错误");
            }
            $omgpath = $_FILES['file']['tmp_name'];
            if ($this->checkMuma($omgpath) == 1) {
                return $this->renderError('您上传的文件为可疑木马，请自重！');
            }
            validate(['image' => 'filesize:10240|fileExt:jpg|image:200,200,jpg'])
                ->check($files);
            $file = $files['file'];
            $savename = \think\facade\Filesystem::disk('public')->putFile('topic', $file);
            $hash = $file->hash('sha1');
        } catch (\think\exception\ValidateException $e) {
            return $this->renderError($e->getMessage());
        }
        $savename = '/storage/' . $savename;

        $savename = str_replace('\\', '/', $savename);

        $pic = Db::name('picture')->where('token', $hash)->find();
        if ($pic) {
            $return['id'] = $pic['id'];
            $return['path'] = imageUrl($pic['imgurl']);
            $return['imgurl'] = $pic['imgurl'];
            unlink('.' . $savename);
            return $this->renderSuccess('上传成功', $return);
        }
        //判断是否开始阿里云存储
        $oss_path = $hash . '.jpg';
        $path = $this->aliyunupload($oss_path, '.' . $savename);
        unlink('.' . $savename);
        $savename = $path;

        //新增数据
        $save_data['imgurl'] = $savename;
        $save_data['token'] = $hash;
        $save_data['addtime'] = time();
        $save_data['status'] = 1;
        $resultId = Db::name('picture')->insertGetId($save_data);
        if ($resultId) {
            $return['id'] = $resultId;
            $return['path'] = imageUrl($savename);
            $return['imgurl'] = $savename;
            return $this->renderSuccess('上传成功', $return);
        } else {
            return $this->renderError('上传失败');
        }

    }

    /**
     * 检测文件是否包含木马
     *
     * @param  $filepath 文件路径
     * @return $status 0为正常 1为可疑木马文件 -1为文件没有上传
     */
    public function checkMuma($filepath)
    {
        $status = 0;
        $tips = array(
            "0" => "文件没问题",
            "1" => "文件为可疑木马文件",
            "-1" => "文件没有上传"
        );
        if (file_exists($filepath)) {
            $resource = fopen($filepath, 'rb');
            $fileSize = filesize($filepath);
            fseek($resource, 0);
            if ($fileSize > 512) { // 取头和尾
                $hexCode = bin2hex(fread($resource, 512));
                fseek($resource, $fileSize - 512);
                $hexCode .= bin2hex(fread($resource, 512));
            } else { // 取全部
                if ($fileSize > 0) {
                    $hexCode = bin2hex(fread($resource, $fileSize));
                } else {
                    return $status = -1;
                }
            }
            fclose($resource);
            /* 通过匹配十六进制代码检测是否存在木马脚本*/
            /* 匹配16进制中的 <% ( ) %> */
            /* 匹配16进制中的 <? ( ) ?> */
            /* 匹配16进制中的 <script | /script> 大小写亦可 */
            if (preg_match("/(3c25.*?28.*?29.*?253e)|(3c3f.*?28.*?29.*?3f3e)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexCode)) {
                $status = 1;
            }
        } else {
            $status = -1;
        }
        return $status;
    }


    //图片上传云存储(阿里云)
    public function aliyunupload($filename, $file_path)
    {
        $upload = new Uploadss;
        $data = $upload->uploadFile($filename, $file_path);
        return $data;
    }


}
